/**
 * @desc 解决浮动运算问题，避免小数点后产生多位数和计算精度损失。
 * 问题示例：2.3 + 2.4 = 4.699999999999999，1.0 - 0.9 = 0.09999999999999998
 */

// 私有变量声明
let _boundaryCheckingState = true

/**
 * 把错误的数据转正
 * strip(0.09999999999999998)=0.1
 */
export function strip(num: number | string, precision: number = 15): number {
  return +parseFloat(Number(num).toPrecision(precision))
}

/**
 * Return digits length of a number
 * @param num Input number
 */
export function digitLength(num: number | string): number {
  const numStr = num.toString()
  const eSplit = numStr.split(/[eE]/)
  const len = (eSplit[0].split('.')[1] || '').length - +(eSplit[1] || 0)
  return len > 0 ? len : 0
}

/**
 * 把小数转成整数，支持科学计数法。如果是小数则放大成整数
 * @param num 输入数
 */
export function float2Fixed(num: number | string): number {
  const numStr = num.toString()
  if (numStr.indexOf('e') === -1) {
    return Number(numStr.replace('.', ''))
  }
  const dLen = digitLength(num)
  return dLen > 0 ? strip(Number(num) * Math.pow(10, dLen)) : Number(num)
}

/**
 * 检测数字是否越界，如果越界给出提示
 * @param num 输入数
 */
function checkBoundary(num: number) {
  if (_boundaryCheckingState) {
    if (num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER) {
      console.warn(`${num} is beyond boundary when transfer to integer, the results may not be accurate`)
    }
  }
}

/**
 * 精确乘法
 */
export function times(num1: number, num2: number, ...others: number[]): number {
  if (others.length > 0) {
    return times(times(num1, num2), others[0], ...others.slice(1))
  }

  const num1Changed = float2Fixed(num1)
  const num2Changed = float2Fixed(num2)
  const baseNum = digitLength(num1) + digitLength(num2)
  const leftValue = num1Changed * num2Changed

  checkBoundary(leftValue)
  return leftValue / Math.pow(10, baseNum)
}

/**
 * 精确加法
 */
export function plus(num1: number, num2: number, ...others: number[]): number {
  if (others.length > 0) {
    return plus(plus(num1, num2), others[0], ...others.slice(1))
  }

  const baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2)))
  return (times(num1, baseNum) + times(num2, baseNum)) / baseNum
}

/**
 * 精确减法
 */
export function minus(num1: number, num2: number, ...others: number[]): number {
  if (others.length > 0) {
    return minus(minus(num1, num2), others[0], ...others.slice(1))
  }

  const baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2)))
  return (times(num1, baseNum) - times(num2, baseNum)) / baseNum
}

/**
 * 精确除法
 */
export function divide(num1: number, num2: number, ...others: number[]): number {
  if (others.length > 0) {
    return divide(divide(num1, num2), others[0], ...others.slice(1))
  }

  const num1Changed = float2Fixed(num1)
  const num2Changed = float2Fixed(num2)

  checkBoundary(num1Changed)
  checkBoundary(num2Changed)
  const numBuer = num1Changed / num2Changed
  const baseNum = strip(Math.pow(10, digitLength(num2) - digitLength(num1)))
  return times(numBuer, baseNum)
}

/**
 * 保留位数
 * @param type 类型 round为四舍五入 floor为向下取 ceil为向上取
 * @param value 数字
 * @param exp 负数表示小数后几位
 */
export function decimalAdjust(type: 'round' | 'floor' | 'ceil', value: number, exp: number): number {
  if (!['round', 'floor', 'ceil'].includes(type)) {
    throw new TypeError("The type of decimal adjustment must be one of 'round', 'floor', or 'ceil'.")
  }

  if (exp % 1 !== 0 || Number.isNaN(value)) {
    return NaN
  } else if (exp === 0) {
    return Math[type](value)
  }

  const [magnitude, exponent = '0'] = value.toString().split('e')
  // 将字符串转换为数字
  const adjustedValue = Math[type](+`${magnitude}e${Number(exponent) - exp}`)

  const [newMagnitude, newExponent = '0'] = adjustedValue.toString().split('e')
  return Number(`${newMagnitude}e${Number(newExponent) + exp}`)
}

/**
 * 四舍五入
 */
export function round(num: number, ratio: number): number {
  const base = Math.pow(10, ratio)
  return divide(Math.round(times(num, base)), base)
}

/**
 * 是否进行边界检查，默认开启
 * @param flag 标记开关，true 为开启，false 为关闭，默认为 true
 */
export function enableBoundaryChecking(flag: boolean = true) {
  _boundaryCheckingState = flag
}

// 默认导出
export default {
  strip,
  plus,
  minus,
  times,
  divide,
  round,
  digitLength,
  float2Fixed,
  enableBoundaryChecking,
  decimalAdjust
}
